package com.rjkj.medicalwaste.ui.xlb

import androidx.lifecycle.ViewModel
import androidx.paging.Pager
import androidx.paging.PagingConfig
import com.rjkj.medicalwaste.bean.CodeType
import com.rjkj.medicalwaste.repository.UserRepository
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.flatMapLatest

import kotlinx.coroutines.flow.mapLatest

class AllUserDataViewModel(private val userRepository: UserRepository):ViewModel() {
    private val selectedType = MutableStateFlow(CodeType.All)
    @ExperimentalCoroutinesApi
    val users = selectedType.flatMapLatest { type->
        Pager(config = PagingConfig(
            pageSize = 20,
            enablePlaceholders = false,
            initialLoadSize = 20
        ), pagingSourceFactory = {
            if(type==CodeType.All){
                userRepository.getAllUserPagingSource()
            }else{
                userRepository.getUserByRoleIdPagingSource(type.string)
            }
        }).flow
    }
    fun setType(codeType: CodeType){
        selectedType.value =  codeType
    }
}